package org.roy.uibase.app;

import java.util.Stack;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;

import org.roy.uibase.event.Event;
import org.roy.uibase.event.EventHandle;
import org.roy.uibase.field.Screen;

public class Application implements EventHandle{
    private MIDlet iMidlet;
    private Stack screens = new Stack();
    
    private static Application instance = null;
    
    public Application(MIDlet aMidlet) {
        iMidlet = aMidlet;
    }
    
    public static Application getApplication(MIDlet aMiDlet){
        if(instance == null){
            instance = new Application(aMiDlet);
        }
        
        return instance;
    }
    
    public void pushScreen(Screen aScreen){
        screens.push(aScreen);
    }
    
    public void exec(){
        Display.getDisplay(iMidlet).setCurrent(new CanvasImpl());
    }
    
    public void dispatchEvent(Event aEvent){
        
    }

    public boolean handleEvent(Event aEvent) {
        return false;
    }
    
    
    private class CanvasImpl extends Canvas{
        protected void paint(Graphics g) {
            Screen screen = (Screen)screens.pop();
            screen.paint(g);
        }
        
        protected void keyPressed(int aKeyCode){
            Event sEvent = new Event(Event.KEY_PRESSED);
            dispatchEvent(sEvent);
        }
        
        protected void keyRepeated(int aKeyCode){
            Event sEvent = new Event(Event.KEY_REPEATED);
            dispatchEvent(sEvent);
        }
        
        protected void keyReleased(int aKeyCode){
            Event sEvent = new Event(Event.KEY_RELEASED);
            dispatchEvent(sEvent);
        }
  
        protected void pointerPressed(int ax, int ay){
            Event sEvent = new Event(Event.POINTER_PRESSED);
            dispatchEvent(sEvent);
        }
        
        protected void pointerDragged(int ax, int ay){
            Event sEvent = new Event(Event.POINTER_DRAGGED);
            dispatchEvent(sEvent);
        }
        
        protected void pointerReleased(int ax, int ay){
            Event sEvent = new Event(Event.POINTER_RELEASED);
            dispatchEvent(sEvent);
        }
    }


}
